package com.itheima.huikebackend.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.huikebackend.dto.ActivityCreateDTO;
import com.itheima.huikebackend.dto.TbActivityDTO;
import com.itheima.huikebackend.entity.TbActivity;
import com.itheima.huikebackend.mapper.TbActivityMapper;
import com.itheima.huikebackend.service.TbActivityService;
import com.itheima.huikebackend.utils.GenRandomYZM;
import com.itheima.huikebackend.vo.Params;
import com.itheima.huikebackend.vo.TbActivityPageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class TbActivityServiceImpl implements TbActivityService {

    private final TbActivityMapper tbActivityMapper;

    @Override
    public Map list(TbActivityDTO tbActivityDTO) {
        PageHelper.startPage(tbActivityDTO.getPageNum(), tbActivityDTO.getPageSize());
        Page<TbActivityPageVO> page = tbActivityMapper.selectList(tbActivityDTO);
        Params params = new Params();
        params.setTotal(page.getTotal());
        params.setPass(page.getTotal());
        params.setReject(0);
        params.setToAudit(0);
        params.setFinish(0);

        Map map =new HashMap();
        map.put("total",page.getTotal());
        map.put("rows",page.getResult());
        map.put("params",params);
        return map;
    }

    @Override
    public void create(ActivityCreateDTO activityCreateDTO) {
        TbActivity tbActivity = new TbActivity();
        BeanUtils.copyProperties(activityCreateDTO,tbActivity);

        if (Objects.isNull(tbActivity.getDiscount())){
            tbActivity.setDiscount(0.0);
        }
        if (Objects.isNull(tbActivity.getVouchers())){
            tbActivity.setVouchers(0);
        }
        tbActivity.setCreateTime(LocalDateTime.now());
        tbActivity.setStatus("1");
        tbActivity.setCode(GenRandomYZM.randomYZM());

        tbActivityMapper.insert(tbActivity);
    }

    @Override
    public void delete(Long id) {
        tbActivityMapper.deleteById(id);
    }

    @Override
    public TbActivityPageVO query(Long id) {
        TbActivityPageVO tbActivityPageVO = tbActivityMapper.selectById(id);
        return tbActivityPageVO;
    }

    @Override
    public void update(ActivityCreateDTO activityCreateDTO) {
        TbActivity tbActivity = new TbActivity();
        BeanUtils.copyProperties(activityCreateDTO,tbActivity);

        tbActivityMapper.updateById(tbActivity);
    }

    @Override
    public List<TbActivity> listSelect(String channel) {
        List<TbActivity> list =  tbActivityMapper.selectByChannel(channel);
        return list;
    }
}
